﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using Common.Utilities;
using OnlineVideos.Data;
using InsertIntoDataBase;
using OnlineVideos.UI;
using PicasaMobileInterface;
using System.IO.IsolatedStorage;
using System.Threading;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using Windows.Common.Data;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using System.Windows.Media;
using HtmlAgilityPack;

namespace OnlineMovies.Views
{
    public class values
    {
        public int PersonID
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public string FlickrPersonImageUrl
        {
            get;
            set;
        }
        public string Description
        {
            get;
            set;
        }
    }
    public partial class AddCast : PhoneApplicationPage
    {
        AddShow addshow = new AddShow();
        public static string imagetype = string.Empty;
        public bool TaskNavigation = false;
        public AutoResetEvent auto = new AutoResetEvent(false);
        public static bool navigated = false;
        public IDictionary<int,string> castdic = new Dictionary<int,string>();
        public List<values> CastList = new List<values>();
        public string ImageUrl = string.Empty;
        public AddCast()
        {
            InitializeComponent();
            Loaded += AddCast_Loaded;
        }

        void AddCast_Loaded(object sender, RoutedEventArgs e)
        {
            if (ResourceHelper.AppName != Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName != Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName != Apps.Story_Time_Pro.ToString())
            LoadAds();
            FlurryWP8SDK.Api.LogEvent("Add Cast Page", true);
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 4);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            Constants.UserImage1 = null;
            Constants.Description.Clear();
            Constants.DownloadTimer.Start();
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            FlurryWP8SDK.Api.EndTimedEvent("Add Cast Page");
            //Constants.selectedindex = lpicrole.SelectedIndex;
            if (e.NavigationMode != NavigationMode.Back)
            {
                Constants.Description.Clear();
                Constants.Description.Append(tblkdes.Text);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
             if (ResourceHelper.AppName == Apps.Indian_Cinema.ToString() || ResourceHelper.AppName == Apps.Indian_Cinema_Pro.ToString() || ResourceHelper.AppName == Apps.Bollywood_Movies.ToString() || ResourceHelper.AppName == Apps.Bollywood_Music.ToString() || ResourceHelper.AppName == Apps.Recipe_Shows.ToString())
            {
                if (e.NavigationMode != NavigationMode.Back)
                {
                    List<string> roles = new List<string>();
                    roles.Add("-- Choose Role --");
                    List<CastRoles> castroles = addshow.CastRoles();
                    foreach (CastRoles role in castroles)
                    {
                        roles.Add(role.Name);
                    }
                    lpicrole.ItemsSource = roles;

                    lpicrole.SelectedIndex = 0;
                }
            }
            else
            {
                desstk.Visibility = Visibility.Collapsed;
                rolestk.Visibility = Visibility.Collapsed;
            }
            //if (e.NavigationMode == NavigationMode.Back)
            //lpicrole.SelectedIndex = Constants.selectedindex;
            if (e.NavigationMode != NavigationMode.Back)
            {

                CastList = Constants.connection.Table<CastProfile>().ToListAsync().Result.Select(i => new values { PersonID = i.PersonID, Name = i.Name, FlickrPersonImageUrl = i.FlickrPersonImageUrl, Description = i.Description }).ToList();
                tblkpersonname.ItemsSource = CastList;
            }
            if (TaskNavigation == false)
            {
                    if (Constants.Description.Length > 0)
                {
                    txtlimit.Visibility = Visibility.Collapsed;
                    tblkdes.Text = Constants.Description.ToString();
                    txtlength.Text = Convert.ToString(tblkdes.Text.Length) + "/" + Convert.ToString(4000);

                }
                //resize person image
                if (Constants.UserImage1 != null && navigated == false)
                {
                    navigated = true;
                    NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + tblkpersonname.Text + "&type=Person", UriKind.Relative));

                }
                else
                {
                    if (Constants.UserImage1 != null && navigated == true)
                    {
                     
                        navigated = false;
                        Constants.UIThread = true;
                        int personid = 0;

                        int minpersonid = AppSettings.MinPersonID;
                        if (Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result != null)
                            personid = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1;
                        else
                            personid = 2;
                        string Personid = Convert.ToString(personid);

                        if (imagetype == "LocalImage")
                        {
                            personlocalimg.Source = ResourceHelper.getpersonTileImage1(Personid + ".jpg");
                            persononlineimg.Source = new BitmapImage(new Uri("/Images/peoplefromonline.png", UriKind.RelativeOrAbsolute));
                        }
                        if (imagetype == "OnlineImage")
                        {
                            persononlineimg.Source = ResourceHelper.getpersonTileImage1(Personid + ".jpg");
                            personlocalimg.Source = new BitmapImage(new Uri("/Images/peoplefromlocal.png", UriKind.RelativeOrAbsolute));
                        }
                  
                        Constants.UIThread = false;
                        Constants.UserImage1 = null;
                    }
                }
            }
            else
            {
                TaskNavigation = false;
            }
            //normal image without resize
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In AddCast.cs file.", ex);
        }
        }
      
        public void uploadImage()
        {           
            try
            {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://picasaweb.google.com/data/feed/api/user/" + CONST.USER);
            request.Method = "POST";
            request.ContentType = "image/png";
            request.Headers["Authorization"] = CONST.PIC_AUTH + CONST.AUTH_Token;
            request.BeginGetRequestStream(new AsyncCallback(GetPicasaStreamCallback), request);
            auto.WaitOne();
        }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in uploadImage Method In AddCast.cs file.", ex);
            }
        }

        private void GetPicasaStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                int personid = 0;
                int minpersonid = AppSettings.MinPersonID;
                if (Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result != null)
                    personid = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1;
                else
                    personid = 2;
                string ImageName = Convert.ToString(personid) + ".jpg";

                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = isoStore.OpenFile("Images" + "/" + "PersonImages" + "/" + ImageName, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read);

                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                byte[] buffer = new byte[fileStream.Length / 4];
                int bytesRead = -1;
                fileStream.Position = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                postStream.Close();
                isoStore.Dispose();
                request.BeginGetResponse(new AsyncCallback(RequestPicasaCompleted), request);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in GetPicasaStreamCallback Method In AddCast.cs file.", ex);
            }
        }

        private void RequestPicasaCompleted(IAsyncResult result)
        {
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(result);
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                XElement MyXMLConfig = XElement.Load(responseReader);
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                ImageUrl = MyXMLConfig.Descendants(atomNS + "content").Attributes().Where(i => i.Name == "src").FirstOrDefault().Value;
                auto.Set();
            }
            catch (Exception ex)
            {
                auto.Set();
                ImageUrl = "http://t1.gstatic.com/images?q=tbn:ANd9GcQyJXo-3YWevA9tkGmycIy5hs1KTgonIT03l-iwKDj09_qLYbivzRgslxlK";
                Exceptions.SaveOrSendExceptions("Exception in RequestPicasaCompleted Method In AddCast.cs file.", ex);
            }

        }
        private void btnsave_Click_1(object sender, EventArgs e)
        {
            try
            {
            if (lpicrole.SelectedIndex != 0 && !string.IsNullOrEmpty(tblkpersonname.Text))
            {
                validrole.Visibility = Visibility.Collapsed;
                valid.Visibility = Visibility.Collapsed;
                if (tblkdes.Text.Length > 4000)
                {

                    txtlimit.Visibility = Visibility.Visible;
                }
                else
                {
                    txtlimit.Visibility = Visibility.Collapsed;
                    personlocalimg.Source = null;
                    persononlineimg.Source = null;
                    
                    BackgroundWorker bg = new BackgroundWorker();
                    bg.DoWork += bg_DoWork;
                    bg.RunWorkerCompleted += bg_RunWorkerCompleted;
                    bg.RunWorkerAsync(tblkpersonname.SelectedItem);
                }
            }
            else
            {

                if (lpicrole.SelectedIndex == 0 && !string.IsNullOrEmpty(tblkpersonname.Text))
                {
                    validrole.Visibility = Visibility.Visible;
                    valid.Visibility = Visibility.Collapsed;
                }
                else if (string.IsNullOrEmpty(tblkpersonname.Text) && lpicrole.SelectedIndex != 0)
                {
                    valid.Visibility = Visibility.Visible;
                    validrole.Visibility = Visibility.Collapsed;
                }
                else
                {
                    validrole.Visibility = Visibility.Visible;
                    valid.Visibility = Visibility.Visible;
                }

            }

        }
            catch (Exception ex)
            {

              Exceptions.SaveOrSendExceptions("Exception in btnsave_Click_1 Method In AddCast.cs file.", ex);
            }
        }

        void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
           
            
            //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
            try
            {
            if (((values)tblkpersonname.SelectedItem) != null)
            {
                    InsertData<ShowCast> insert = new InsertData<ShowCast>();
                    insert.ParameterList = new ShowCast();
                    insert.ParameterList.ShowID = AppSettings.ShowUniqueID;
                    insert.ParameterList.PersonID = ((values)tblkpersonname.SelectedItem).PersonID;
                    if (ResourceHelper.AppName == Apps.Kids_TV_Shows.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Animation_Planet.ToString() || ResourceHelper.AppName == Apps.Kids_TV.ToString() || ResourceHelper.AppName == Apps.Yoga_and_Health.ToString().Replace("and", "&"))
                        insert.ParameterList.RoleID = 0;
                    else
                    {
                        string name = lpicrole.SelectedItem.ToString();
                        List<CastRoles> rolesforcast = addshow.CastRoles();
                        insert.ParameterList.RoleID = rolesforcast.Where(i => i.Name == name).FirstOrDefault().RoleID;
                    }
                    insert.Insert();
               
            }
            else
            {
                InsertData<ShowCast> insert = new InsertData<ShowCast>();
                insert.ParameterList = new ShowCast();
                insert.ParameterList.ShowID = AppSettings.ShowUniqueID;
                int personid = 0;
                int minpersonid = AppSettings.MinPersonID;
                if (Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result != null)
                    personid = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1;
                else
                    personid = 2;

                insert.ParameterList.PersonID = personid;
                if (ResourceHelper.AppName == Apps.Kids_TV_Shows.ToString() || ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Animation_Planet.ToString() || ResourceHelper.AppName == Apps.Kids_TV.ToString() || ResourceHelper.AppName == Apps.Yoga_and_Health.ToString().Replace("and", "&"))
                    insert.ParameterList.RoleID = 0;
                else
                {
                    string name = lpicrole.SelectedItem.ToString();
                    List<CastRoles> rolesforcast = addshow.CastRoles();
                    insert.ParameterList.RoleID = rolesforcast.Where(i => i.Name == name).FirstOrDefault().RoleID;
                }
                insert.Insert();
                InsertData<CastProfile> insert1 = new InsertData<CastProfile>();
                insert1.ParameterList = new CastProfile();
                insert1.ParameterList.Name = tblkpersonname.Text;
                insert1.ParameterList.Description = tblkdes.Text;
                insert1.ParameterList.PersonID = insert.ParameterList.PersonID;

                insert1.ParameterList.FlickrPersonImageUrl = ImageUrl;
                insert1.ParameterList.FlickrPanoramaImageUrl = "";
                insert1.Insert();
            }
            Constants.Description.Clear();
            tblkdes.Text = string.Empty;
            Constants.UserImage1 = null;
            Constants.DownloadTimer.Start();
            if (ResourceHelper.AppName == Apps.Kids_TV_Shows.ToString() ||  ResourceHelper.AppName == Apps.Kids_TV_Pro.ToString() || ResourceHelper.AppName == Apps.Recipe_Shows.ToString() || ResourceHelper.AppName == Apps.Animation_Planet.ToString() || ResourceHelper.AppName == Apps.Kids_TV.ToString() || ResourceHelper.AppName == Apps.Yoga_and_Health.ToString().Replace("and", "&"))
                NavigationService.Navigate(new Uri("/Views/ShowDetails.xaml?navigationvalue=" + Constants.navigationvalue + "&pivotindex=" + 1, UriKind.Relative));
                else if (ResourceHelper.AppName == Apps.Bollywood_Music.ToString())
                NavigationService.Navigate(new Uri("/Views/MusicDetail.xaml?navigationvalue=" + Constants.navigationvalue + "&pivotindex=" + 3, UriKind.Relative));
            else
                    NavigationService.Navigate(new Uri("/Views/Details.xaml?navigationvalue=" + Constants.navigationvalue + "&pivotindex=" + 1, UriKind.Relative));
            //NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in bg_RunWorkerCompleted Method In AddCast.cs file.", ex);
            }

        }
        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (e.Argument == null)
            {
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                int personid = 0;
                int minpersonid = AppSettings.MinPersonID;
                if (Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result != null)
                    personid = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID < minpersonid).OrderByDescending(i => i.PersonID).FirstOrDefaultAsync()).Result.PersonID + 1;
                else
                    personid = 2;
                string ImageName = Convert.ToString(personid) + ".jpg";
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (isoStore.FileExists(Constants.PersonImagePath + ImageName))
                {
                    ImageUrl = string.Empty;
                    List<BlogCategoryTable> blogcategorytable = addshow.BlogCategoryTable();
                    BlogCategoryTable bt = blogcategorytable.Where(i => i.BlogType == "people").FirstOrDefault();
                    if (NetworkHelper.IsNetworkAvailableForDownloads())
                    {
                        PicasaInterface pi = new PicasaInterface(bt.BlogUserName, bt.BlogPassword);
                        uploadImage();
                    }
                    else
                        ImageUrl = "http://t1.gstatic.com/images?q=tbn:ANd9GcQyJXo-3YWevA9tkGmycIy5hs1KTgonIT03l-iwKDj09_qLYbivzRgslxlK";
                }
                else
                {
                    ImageUrl = "http://t1.gstatic.com/images?q=tbn:ANd9GcQyJXo-3YWevA9tkGmycIy5hs1KTgonIT03l-iwKDj09_qLYbivzRgslxlK";
                }
                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in bg_DoWork Method In AddCast.cs file.", ex);
            }
        }
        private void imgTitle_MouseEnter(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

        private void personlocalimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

            imagetype = "LocalImage";
            PhotoChooserTask task = new PhotoChooserTask();
            task.Completed += task_Completed;
            task.Show();
            TaskNavigation = true;
        }
        void task_Completed(object sender, PhotoResult e)
        {
            try
            {
            if (e.TaskResult == TaskResult.OK)
            {
                Constants.UserImage1 = new BitmapImage();
                Constants.UserImage1.SetSource(e.ChosenPhoto);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + tblkpersonname.Text, UriKind.Relative));

                });

                // userimg.Source = bitmapimage;
            }
            }
            catch (Exception ex)
            {
                
                   Exceptions.SaveOrSendExceptions("Exception in task_Completed Method In AddCast.cs file.", ex);
            }
        }

        private void persononlineimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            imagetype = "OnlineImage";
            WebClient wb = new WebClient();
                wb.DownloadStringAsync(new Uri(" http://www.bing.com/images/search?q=" + tblkpersonname.Text, UriKind.Absolute));
            wb.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wb_DownloadStringCompleted);
        }
        void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    string PageHtml = e.Result.ToString();
                    Constants.OnlineImageUrls.Clear();
                    Constants.OnlineImageUrls = GetImages(PageHtml);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                    });
                }
            }
            catch (Exception ex)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                });
                Exceptions.SaveOrSendExceptions("Exception in wb_DownloadStringCompleted Method In AddCast.cs file.", ex);
            }
        }

        public ObservableCollection<string> GetImages(string input)
        {
            ObservableCollection<string> list = new ObservableCollection<string>();
            try
            {
              
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(input);

            foreach (HtmlNode node in doc.DocumentNode.SelectNodes(" //img"))
            {
                if (node.OuterHtml.Contains("src") || node.OuterHtml.Contains("data-src") || node.OuterHtml.Contains("dfr-src") || node.OuterHtml.Contains("deferredsrc") || node.OuterHtml.Contains("src2"))
                {
                    if (((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["src2"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["src2"] : node.Attributes["data-src"] : node.Attributes["src"]).Value.StartsWith("http"))
                    {


                        list.Add(((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["src2"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["src2"] : node.Attributes["data-src"] : node.Attributes["src"]).Value);
                    }

                }
                }
              
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in GetImages Method In AddCast.cs file.", ex);
            }
            return list;
        }


        private void persondes_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/UserBrowserPage.xaml?querytext=Cast&searchquery=" + tblkpersonname.Text, UriKind.RelativeOrAbsolute));
        }

        private void edit_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Constants.Description.Clear();
            Constants.Description.Append(tblkdes.Text);
            NavigationService.Navigate(new Uri("/Views/Description.Xaml", UriKind.Relative));
        }

        private void tblkdes_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            txtlimit.Visibility = Visibility.Collapsed;
            txtlength.Text = Convert.ToString(tblkdes.Text.Length) + "/" + Convert.ToString(4000);
        }

        private void tblkpersonname_KeyUp_1(object sender, System.Windows.Input.KeyEventArgs e)
        {

        }

        private void tblkpersonname_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {
            if (tblkpersonname.SelectedItem != null)
            {
                tblkdes.Text = ((values)tblkpersonname.SelectedItem).Description;
                    persononlineimg.Source = new BitmapImage(new Uri(((values)tblkpersonname.SelectedItem).FlickrPersonImageUrl, UriKind.RelativeOrAbsolute));
                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in tblkpersonname_SelectionChanged_1 Method In AddCast.cs file.", ex);
            }
        }

        private void TextBlock_Loaded_1(object sender, RoutedEventArgs e)
        {
            TextBlock Tb = sender as TextBlock;
            if (Tb.Text == "-- Choose Role --")
            {
                Tb.Visibility = Visibility.Collapsed;
                Tb.Loaded -= TextBlock_Loaded_1;
            }
        }
    }
}